package com.shujia.scala

import java.io.{BufferedReader, FileReader}

import scala.collection.mutable.ListBuffer
import scala.io.Source

object Demo16Worcount {

  def main(args: Array[String]): Unit = {


    /**
      * 1、读取数据
      *
      */


    val list = new ListBuffer[String]

    val bf = new BufferedReader(new FileReader("scala/data/words.txt"))

    var line = bf.readLine()

    while (line != null) {

      //将元素增加到list中
      list += line
      //读取下一行
      line = bf.readLine()
    }

    //println(list)


    /**
      * scala 读取文件
      *
      */

    val source = Source.fromFile("scala/data/words.txt")

    //读取所有行  转换成list
    val lines: List[String] = source.getLines().toList

    /**
      * map  闯入一行 返回一行
      *
      * flatMap  传入一行返回多行   每一个单词一行
      * 1、先对元素进行map操作
      * 2、在将数组中的元素进行扁平化
      *
      */

    val words: List[String] = lines.flatMap(line => line.split(","))


    //分组  以单词进行分组
    val groupBy: Map[String, List[String]] = words.groupBy(word => word)


    //统计单词数量
    val count = groupBy.map(kv => {
      val word = kv._1

      val values = kv._2

      val count = values.length

      word + "\t" + count
    })


    count.foreach(println)


    //链式调用
    Source
      .fromFile("scala/data/words.txt")
      .getLines()
      .toList
      .flatMap(word => word.split(","))
      .groupBy(word => word)
      .map(kv => kv._1 + "\t" + kv._2.length)
      .foreach(println)


  }

}
